import {Controller, Get, Post, Put, Body, Param, Query, UseGuards, UseInterceptors, UploadedFile} from '@nestjs/common';
import {FileInterceptor} from '@nestjs/platform-express';
import {ApiTags, ApiOperation, ApiConsumes, ApiBody} from '@nestjs/swagger';
import {RecipeService} from './recipe.service';
import {CreateRecipeDto, RecipeFilterDto} from './dto/recipe.dto';
import {JwtAuthGuard} from '../user/jwt-auth.guard';
import {diskStorage} from 'multer';
import {extname} from 'path';
import {DailyRecommendation} from './types/recipe.types';

@ApiTags('菜谱')
@Controller('recipes')
@UseGuards(JwtAuthGuard)
export class RecipeController {
  constructor(private readonly recipeService: RecipeService) {
  }
  
  @Get('all')
  @ApiOperation({summary: '获取所有菜谱'})
  async getAllRecipes() {
    return this.recipeService.getAllRecipes();
  }
  
  @Post('upload-image')
  @ApiOperation({summary: '上传菜品图片'})
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads/images',
        filename: (req, file, callback) => {
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          callback(null, uniqueSuffix + extname(file.originalname));
        },
      }),
      fileFilter: (req, file, callback) => {
        if (!file.originalname.match(/\.(jpg|jpeg|png|gif)$/)) {
          return callback(new Error('只允许上传图片文件！'), false);
        }
        callback(null, true);
      },
      limits: {
        fileSize: 5 * 1024 * 1024, // 限制5MB
      },
    }),
  )
  async uploadImage(@UploadedFile() file: Express.Multer.File) {
    const imageUrl = `https://wufeng98.cn/cookApi/images/${file.filename}`;
    return {imageUrl};
  }
  
  @Post()
  @ApiOperation({summary: '创建新菜谱'})
  async createRecipe(@Body() createRecipeDto: CreateRecipeDto) {
    return this.recipeService.createRecipe(createRecipeDto);
  }
  
  @Put(':id')
  @ApiOperation({summary: '修改菜谱'})
  async updateRecipe(
    @Param('id') id: string,
    @Body() updateRecipeDto: CreateRecipeDto,
  ) {
    return this.recipeService.updateRecipe(id, updateRecipeDto);
  }
  
  @Get('daily-recommendation')
  @ApiOperation({summary: '获取每日推荐菜谱'})
  async getDailyRecommendation(
    @Query() filter: RecipeFilterDto,
    @Query('familyId') familyId: string,
  ): Promise<DailyRecommendation> {
    return this.recipeService.getDailyRecommendation(filter, familyId);
  }
  
  @Get('weekly-plan')
  @ApiOperation({summary: '获取周计划'})
  async getWeeklyPlan(@Query('familyId') familyId: string) {
    return this.recipeService.generateWeeklyPlan(familyId);
  }
  
  @Get(':id')
  @ApiOperation({summary: '获取菜谱详情'})
  async getRecipe(@Param('id') id: string) {
    return this.recipeService.getRecipeById(id);
  }
}
